<template>
  <Card size="small" :bordered="false" class="w-4/4 w-full !mt-0 !rounded-lg !p-6px">
    <template #title>
      <div class="flex items-center cursor-pointer" @click="goRoute">
        <div>{{ props.datalist?.name }}</div>
        <ArrowRightOutlined v-if="props.datalist?.canGo" class="ml-10px" />
      </div>
    </template>
    <template #extra>
      <div class="flex">
        <EllipticTabs
          v-if="props.datalist?.tabsant"
          :tablist="props.datalist?.tabsant"
          @change="changeTabs"
        />
        <a-button
          v-if="props.datalist?.ant && hasPermission('TENANT_ADMIN')"
          size="default"
          type="primary"
          class="ml-10px"
          @click="addTbdashboards"
        >
          添加仪表盘
        </a-button>
      </div>
    </template>
    <BasicTable v-if="props.datalist?.ant" @register="registerRefundTable" class="!p-0" />
    <div v-if="!props.datalist?.ant">
      <div>历史30天数据</div>
      <VisitAnalysis :activeTab="activeTab" :echartsList="echartsList" />
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue';
  import EllipticTabs from './EllipticTabs.vue';
  import VisitAnalysis from './VisitAnalysis.vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { refundTableSchema } from './tableData';
  import { Card } from 'ant-design-vue';
  import { ArrowRightOutlined } from '@ant-design/icons-vue';
  import { useGo } from '/@/hooks/web/usePage';
  import dayjs from 'dayjs';
  import { getUserDashboards } from '/@/api/thingsborad/home/home';
  import { usePermission } from '/@/hooks/web/usePermission';
  const emits = defineEmits(['timeValueSelect', 'tabs-change']);
  const props = defineProps({
    datalist: {
      type: Object,
    },
    echartsList: {
      type: Array,
      default: () => [],
    },
  });

  const { hasPermission } = usePermission();
  const activeTab = ref<number>(1);
  let tableData = ref<Array<any>>([]);
  const timeValue = ref<any>([]);
  const go = useGo();
  const changeTabs = (e: number) => {
    activeTab.value = e;
    emits('tabs-change', e);
  };
  onMounted(() => {
    // 获取当前时间戳
    const currentDate = dayjs();
    // 计算30天前的时间戳
    const thirtyDaysAgoTimestamp = dayjs().subtract(30, 'day');
    timeValue.value.push(currentDate);
    timeValue.value.push(thirtyDaysAgoTimestamp);
  });
  watch(
    () => timeValue.value,
    (nVal) => {
      emits('timeValueSelect', nVal);
    },
  );
  const [registerRefundTable] = useTable({
    api: getUserDashboards,
    afterFetch: (res) => {
      tableData.value = [];

      res.forEach((item) => {
        tableData.value.push({
          title: item.title,
          lastVisited: getTime(item.lastVisited),
        });
      });
      return tableData.value;
    },
    fetchSetting: {
      listField: 'last',
    },
    columns: refundTableSchema,
    pagination: false,
    showIndexColumn: false,
    ...(hasPermission('TENANT_ADMIN') && { scroll: { y: 120 } }),
  });

  const goRoute = () => {
    switch (props.datalist?.key) {
      case 'dashboard':
        go('/tb-dashboards/dashboards');
        break;
    }
  };

  function getTime(lastTime: any) {
    // 假设我们有两个时间戳
    const timestamp1: any = dayjs();
    const timestamp2 = lastTime; // 另一个时间戳

    // 将时间戳转换为 Day.js 对象
    const date1 = dayjs.unix(timestamp1 / 1000); // 如果是毫秒转为秒
    const date2 = dayjs.unix(timestamp2 / 1000);

    // 计算时间差（以毫秒为单位）
    let differenceInMilliseconds: any = Math.abs(date2.diff(date1));

    // 转换为相应的单位
    let seconds = Math.floor(differenceInMilliseconds / 1000);
    differenceInMilliseconds -= seconds * 1000;
    let minutes = Math.floor(seconds / 60);
    seconds %= 60;
    let hours = Math.floor(minutes / 60);
    minutes %= 60;
    let days = Math.floor(hours / 24);
    hours %= 24;

    // 计算年、月、周则比较复杂，因为涉及到不同月份天数和是否闰年的问题
    // 下面是一个非常粗略的估算，仅用于演示，实际应用中请使用更精确的算法或第三方库辅助计算
    let months = Math.floor(days / 30); // 简单按30天平均估算
    let years = Math.floor(months / 12); // 简单按12个月估算
    let weeks = Math.floor(days / 7); // 计算周数

    if (years !== 0) {
      return `${years}年之前`;
    } else {
      if (months !== 0) {
        return `${months % 12}月之前`;
      } else {
        if (weeks !== 0) {
          return `${weeks}周之前`;
        } else {
          if (days !== 0) {
            return `${days}天之前`;
          } else {
            if (hours !== 0) {
              return `${hours}小时之前`;
            } else {
              if (minutes !== 0) {
                return `${minutes}分钟之前`;
              } else {
                if (seconds !== 0) {
                  return `${seconds}秒之前`;
                }
              }
            }
          }
        }
      }
    }
  }
  function addTbdashboards() {
    go({
      name: 'tbdashboards',
      params: {
        action: '添加仪表盘',
        key: '首页',
      },
    });
  }
</script>
